package com.tuanchau.android.englishtooltip.ui.activity;

import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.tuanchau.android.englishtooltip.Global;
import com.tuanchau.android.englishtooltip.R;

public class WordDetailActivity extends Activity implements OnClickListener,
		OnInitListener {

	public final int SR_DETAIL_EDIT = 2;

	private ImageView imageView;
	private TextView txtWord, txtMean, txtPronunciation, txtType;
	private String strWord, strMean, strPronunciation, strType;
	private byte[] image;
	private boolean isEditted = false;
	private int wordPosition;

	private TextToSpeech tts;

	private SharedPreferences pref;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_word_detail);

		initView();

	}

	@Override
	public void onDestroy() {
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}
		super.onDestroy();
	}

	private void initView() {
		Bundle bundle = getIntent().getExtras();
		imageView = (ImageView) findViewById(R.id.activity_word_detail_image);
		txtWord = (TextView) findViewById(R.id.activity_word_detail_word);
		txtMean = (TextView) findViewById(R.id.activity_word_detail_mean);
		txtPronunciation = (TextView) findViewById(R.id.activity_word_detail_pronunciation);
		Typeface font = Typeface
				.createFromAsset(getAssets(), "courier_new.ttf");
		txtPronunciation.setTypeface(font);

		txtType = (TextView) findViewById(R.id.activity_word_detail_type);

		wordPosition = bundle.getInt(Global.KEY_WORD_POSITION);
		strWord = bundle.getString(Global.KEY_WORD);
		strMean = bundle.getString(Global.KEY_MEAN);
		image = bundle.getByteArray(Global.KEY_IMAGE);
		strPronunciation = bundle.getString(Global.KEY_PRONUNCIATION);
		strType = bundle.getString(Global.KEY_TYPE);

		initViewValue();

		// findViewById(R.id.activity_word_detail_edit).setOnClickListener(this);
		// findViewById(R.id.activity_word_detail_back).setOnClickListener(this);
		// findViewById(R.id.activity_word_detail_speech).setOnClickListener(this);
		findViewById(R.id.activity_word_detail_exit).setOnClickListener(this);
		imageView.setOnClickListener(this);

		tts = null;

		pref = getSharedPreferences(Global.PREF_FILE_NAME, MODE_PRIVATE);
	}

	private void initViewValue() {
		txtWord.setText(strWord);
		txtMean.setText(strMean);
		if (strPronunciation.length() > 0)
			txtPronunciation.setText("/" + strPronunciation + "/");
		txtType.setText(strType);

		if (image != null) {
			Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0,
					image.length);
			imageView.setImageBitmap(bitmap);
		} else {
			imageView.setImageResource(R.drawable.english_tip_icon_100);
		}
	}

	// ---------------- create menu -------------------//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.word_detail_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_word_detail_edit:
			onEditClicked();
			return true;
		case R.id.menu_word_detail_setting:
			onSettingItemClicked();
			return true;
		default:
			return false;
		}
	}

	@Override
	public void onClick(final View v) {
		if (v.getId() == R.id.activity_word_detail_exit) {
			setResultData(true);
			finish();
		} else {
			onSpeechClicked();
		}
	}

	private void onEditClicked() {
		final Intent intent = new Intent(this, EditWordActivity.class);
		intent.putExtra(Global.STATE_CODE, Global.STATE_EDIT);
		intent.putExtra(Global.KEY_WORD, strWord);
		intent.putExtra(Global.KEY_PRONUNCIATION, strPronunciation);
		intent.putExtra(Global.KEY_TYPE, strType);
		intent.putExtra(Global.KEY_IMAGE, image);
		intent.putExtra(Global.KEY_MEAN, strMean);

		isEditted = true;

		startActivityForResult(intent, SR_DETAIL_EDIT);

	}

	@Override
	public void onBackPressed() {
		setResultData(false);
		finish();
	}

	private void onSpeechClicked() {

		if (tts == null) {
			Intent checkIntent = new Intent();
			checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
			startActivityForResult(checkIntent, Global.TEXT_TO_SPEECH_CHECK);
		} else {
			speak();
		}

	}

	private void onSettingItemClicked() {
		Intent intent = new Intent(getApplicationContext(),
				SettingActivity.class);
		startActivity(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case SR_DETAIL_EDIT:
			if (resultCode == Activity.RESULT_OK) {
				onEditResult(data);
			}
			break;
		case Global.TEXT_TO_SPEECH_CHECK:
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				tts = new TextToSpeech(this, this);
			} else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		default:
			break;
		}
	}

	public void onEditResult(Intent data) {
		int state = data.getIntExtra(Global.STATE_CODE, Global.STATE_EDIT);
		if (state == Global.STATE_NOCHANGE) {
			isEditted = false;
		} else {
			strWord = data.getStringExtra(Global.KEY_WORD);
			strPronunciation = data.getStringExtra(Global.KEY_PRONUNCIATION);
			strType = data.getStringExtra(Global.KEY_TYPE);
			image = data.getByteArrayExtra(Global.KEY_IMAGE);
			strMean = data.getStringExtra(Global.KEY_MEAN);
			isEditted = true;
			initViewValue();
		}

	}

	@Override
	protected void onStop() {
		setResultData(true);
		super.onStop();
	}

	private void setResultData(boolean doExit) {
		Intent result = new Intent();
		result.putExtra(Global.KEY_DO_EXIT, doExit);
		if (!isEditted) {
			result.putExtra(Global.STATE_CODE, Global.STATE_NOCHANGE);
		} else {
			result.putExtra(Global.STATE_CODE, Global.STATE_EDIT);
			result.putExtra(Global.KEY_WORD_POSITION, wordPosition);
			result.putExtra(Global.KEY_WORD, strWord);
			result.putExtra(Global.KEY_PRONUNCIATION, strPronunciation);
			result.putExtra(Global.KEY_TYPE, strType);
			result.putExtra(Global.KEY_IMAGE, image);
			result.putExtra(Global.KEY_MEAN, strMean);
		}
		setResult(Activity.RESULT_OK, result);
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			int result = tts.setLanguage(Locale.US);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
			} else {
				speak();
			}
		}

	}

	private void speak() {

		AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		int volume = pref.getInt(Global.PREF_KEY_VOLUME, 8);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
		tts.speak(strWord, TextToSpeech.QUEUE_FLUSH, null);
	}
}
